//
//  StatusListViewModel.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/9.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import Foundation
import SDWebImage
///微博数据列表数据模型
class StatusListViewModel {
    
    /// 微博模型数组
    lazy var statusList = [StatusViewModel]()
    /// 下载用户信息
    func loadStatus(isPullUp isPullUp:Bool,finished:(isSuccessed:Bool)->()){
//         下拉刷下,数组中第一个微博 id
        let since_id = isPullUp ? 0:(statusList.first?.status.id ?? 0)
//         上拉刷新,数组中最后一个微博 id
        let max_id = isPullUp ? (statusList.last?.status.id ?? 0):0
        StatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
            guard let array = array else{
                finished(isSuccessed: false)
                return
            }
//            字典转模型
            var arrayM  = [StatusViewModel]()
            for dict in array {
                arrayM.append(StatusViewModel(status: Status(dict:dict)))
            }
//            拼接数据
            if max_id > 0 {
                // 上拉刷新，将新数据拼接在当前数组的末尾
                self.statusList += arrayM
            } else {
                // 下拉或默认刷新，将新数据追加在当前数组的前面
                self.statusList = arrayM + self.statusList
            }
            
            
//            5 缓存单张图片
            // 4. 缓存图片
            self.cacheSingleImage(arrayM, finished: finished)
            
        }
    }
    /// 缓存单张图片
    private func cacheSingleImage(dataList:[StatusViewModel],finished:(isSuccessd:Bool)->()){
        
//        1 创建调度组
         let group = dispatch_group_create()
        var lentghData = 0
        
//        2 遍历视图模型数组
        for vm in dataList{
            if vm.thumbnailUrls?.count != 1{
                continue
            }
//          获取 URL
            let url = vm.thumbnailUrls![0]
            print("开始缓存图片")
//            入组
            dispatch_group_enter(group)
//            下载图片
            SDWebImageManager.sharedManager().downloadImageWithURL(
                url,
                options: [],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                    if let img = image,let data = UIImagePNGRepresentation(img){
                    lentghData += data.length
                    }
//              出组
                dispatch_group_leave(group)
            })
            
        }

//        3 监听调度完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存完成")
            
            
            finished(isSuccessd: true)
        }
        
    }
}